package org.cqu_proj.demo.service;


import org.cqu_proj.demo.dao.UserRepository;
import org.cqu_proj.demo.entity.Counter;
import org.cqu_proj.demo.entity.Rating;
import org.cqu_proj.demo.entity.User;
import org.cqu_proj.demo.dto.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserService {
    // 配置文件中读取图片上传目录
    @Value("${user.profile.upload-dir}")
    private String uploadDir;
    //照片文件的存储路径
    private String storageFile="D:/work/pic/";

    private MongoTemplate mongoTemplate;

    public UserRepository userRepository;
    private final UserFeaturesService userFeaturesService;
    private final RatingService ratingService;
    private final MovieFeaturesService movieFeaturesService;

    @Autowired
    public UserService(MongoTemplate mongoTemplate, UserRepository userRepository, UserFeaturesService userFeaturesService, RatingService ratingService, MovieFeaturesService movieFeaturesService) {
        this.mongoTemplate = mongoTemplate;
        this.userRepository = userRepository;
        this.userFeaturesService = userFeaturesService;
        this.ratingService = ratingService;
        this.movieFeaturesService = movieFeaturesService;
    }
    // <editor-fold desc="用户账号管理">
    // 注册用户
    public ResponseResult<User> registerUser(User user) {
        // 检查邮箱是否为空且已被注册
        if (user.getUserEmail() != null && !user.getUserEmail().isEmpty()) {
            if (userRepository.findByUserEmail(user.getUserEmail()).isPresent()) {
                return ResponseResult.failure(205, "该邮箱已被使用！");
            }
        }

        // 检查手机号是否为空且已被注册
        if (user.getUserPhone() != null && !user.getUserPhone().isEmpty()) {
            if (userRepository.findByUserPhone(user.getUserPhone()).isPresent()) {
                return ResponseResult.failure(205, "该号码已被使用！");
            }
        }

        user.setUserGender("未知");
        user.setUserProfileUrl("");
        user.setUserRegisterTime(new Date());  // 设置当前时间
        user.setUserIntroduce("这个人很懒，什么也没留下");
        user.setUserModifyTime(new Date());
        user.setUserNickname("默认昵称");
        user.setUserRealname("");
        user.setUserId(getNextUserId());
        int userId=user.getUserId();
        double targetAvg=0.421;
        this.userFeaturesService.saveUserFeatureToDatabase(userId,userFeaturesService.initUserFeature(userId, targetAvg));
        //this.userFeaturesService.handleUserFeatures(user);

        // 保存用户信息
        User savedUser = userRepository.save(user);

        user.setUserPassword("");  // 密码不返回给客户端
        // 返回成功的响应
        return ResponseResult.success(savedUser);
    }

    // 用户登录
    public ResponseResult<User> loginUser(User user) {
        // 检查传入的 User 对象中是否包含有效的邮箱或手机号
        Optional<User> userOptional = Optional.empty();

        if (user.getUserEmail() != null && !user.getUserEmail().isEmpty()) {
            // 尝试通过邮箱查找用户
            userOptional = userRepository.findByUserEmail(user.getUserEmail());
        } else if (user.getUserPhone() != null && !user.getUserPhone().isEmpty()) {
            // 如果没有邮箱，尝试通过手机号查找用户
            userOptional = userRepository.findByUserPhone(user.getUserPhone());
        }

        // 如果邮箱和手机号都没有提供，返回用户未找到的错误
        if (!userOptional.isPresent()) {
            return ResponseResult.failure(201, "User not found!");
        }

        //查询到的用户信息
        User foundUser = userOptional.get();

        // 验证密码是否正确
        if (!foundUser.getUserPassword().equals(user.getUserPassword())) {
            return ResponseResult.failure(202, "Invalid password!");
        }

        // 更新最近登录时间
        foundUser.setUserLastloginTime(new Date());
        userRepository.save(foundUser);

        // 重新从数据库查询用户信息，确保返回的是最新的用户数据
        Optional<User> updatedUserOptional = userRepository.findByUserId(foundUser.getUserId());
        if (!updatedUserOptional.isPresent()) {
            return ResponseResult.failure(404, "User not found after update!");
        }

        User updatedUser = updatedUserOptional.get();

        updatedUser.setUserPassword("");
        // 返回成功响应，包括登录后的用户信息
        if(this.userFeaturesService.handleUserFeatures(updatedUser))
            return  new ResponseResult<User>(200,"用户已选择电影偏好",updatedUser);
        else
            return  new ResponseResult<User>(203,"用户未选择电影偏好",updatedUser);

    }

    // 修改用户信息
    public ResponseResult<User> updateUserInfo(User updatedUser) {
        // 根据 userId 查找用户
        Optional<User> userOptional = userRepository.findByUserId(updatedUser.getUserId());
        if (!userOptional.isPresent()) {
            return ResponseResult.failure(404, "User not found!");
        }

        // 获取当前用户信息
        User user = userOptional.get();

        // 检查传入的 userPhone 是否已存在于其他用户中
        if (updatedUser.getUserPhone() != null && !updatedUser.getUserPhone().equals(user.getUserPhone())) {
            Optional<User> userWithPhone = userRepository.findByUserPhone(updatedUser.getUserPhone());
            if (userWithPhone.isPresent()) {
                return ResponseResult.failure(400, "该号码已经被注册!");
            }
        }

        // 检查传入的 userEmail 是否已存在于其他用户中
        if (updatedUser.getUserEmail() != null && !updatedUser.getUserEmail().equals(user.getUserEmail())) {
            Optional<User> userWithEmail = userRepository.findByUserEmail(updatedUser.getUserEmail());
            if (userWithEmail.isPresent()) {
                return ResponseResult.failure(400, "该邮箱已经被注册!");
            }
        }

        // 更新用户信息
        user.setUserNickname(updatedUser.getUserNickname());
        user.setUserIntroduce(updatedUser.getUserIntroduce());
        user.setUserRealname(updatedUser.getUserRealname());
        user.setUserGender(updatedUser.getUserGender());
        user.setUserPhone(updatedUser.getUserPhone());
        user.setUserEmail(updatedUser.getUserEmail());
        user.setUserBirthday(updatedUser.getUserBirthday());

        // 更新修改时间
        user.setUserModifyTime(new Date());

        // 保存更新后的用户信息
        userRepository.save(user);

        //删去用户密码
        user.setUserPassword("");

        // 返回成功响应，包括修改后的用户信息
        return ResponseResult.success(user);
    }

    // 用户注销
    public ResponseResult<Void> deleteUser(int userId) {
        // 查找用户
        Optional<User> userOptional = userRepository.findByUserId(userId);

        // 如果用户未找到
        if (!userOptional.isPresent()) {
            return ResponseResult.failure(404, "User not found!");
        }

        // 删除用户
        userRepository.deleteByUserId(userId);

        // 返回成功响应，data字段为空
        return ResponseResult.success(null);
    }

    //上传头像并修改数据库数据
    public ResponseResult<String> uploadProfile(int userId, MultipartFile file) {
        // 1. 获取用户信息
        Optional<User> userOptional = userRepository.findByUserId(userId);
        if (!userOptional.isPresent()) {

            return ResponseResult.failure(404, "用户不存在!");
        }
        User user = userOptional.get();
        String profileUrl=upload(file);
        // 6. 更新用户头像 URL
        user.setUserProfileUrl(profileUrl);
        // 7. 保存更新后的用户信息
        userRepository.save(user);
        // 8. 返回上传成功的响应，包含头像的 URL
        return ResponseResult.success(profileUrl);
    }
    private String upload(MultipartFile multipartFile){
        // 生成一个随机的名称，避免文件名重复
        UUID uuid = UUID.randomUUID();
        // 获取原文件名称
        String originalFileName = multipartFile.getOriginalFilename();
        // 获取原文件的后缀
        String fileSuffix = originalFileName.substring(originalFileName.lastIndexOf('.'));
        // 保存文件
        File file = new File(this.storageFile + uuid + fileSuffix);
        try {
            multipartFile.transferTo(file);
        } catch (Exception e) {
            System.out.println("图片上传出现问题");
            e.printStackTrace();
            return null;
        }
        return uuid+fileSuffix;
    }


    // 修改用户密码
    public ResponseResult<Void> updatePassword(User user) {
        Optional<User> userOptional = userRepository.findByUserId(user.getUserId());

        if (userOptional.isPresent()) {
            User existingUser = userOptional.get();
            existingUser.setUserPassword(user.getUserPassword());  // 直接设置新密码

            userRepository.save(existingUser);  // 保存修改后的用户信息

            return ResponseResult.success(null);  // 返回成功响应
        } else {
            return ResponseResult.failure(404, "用户不存在");  // 用户未找到
        }
    }
    //实现userId 自增
    private int getNextUserId() {
        System.out.println("进入getNexg1");
        // 获取并递增计数器
        Query query = new Query(Criteria.where("_id").is("userId"));
        Update update = new Update().inc("seq", 1);
        FindAndModifyOptions options = new FindAndModifyOptions().returnNew(true);

        // 获取并递增计数器中的值
        Counter counter = mongoTemplate.findAndModify(query, update, options, Counter.class);

        if (counter == null) {
            throw new RuntimeException("Counter not found");
        }

        return counter.getSeq();
    }
    // </editor-fold>
    //查询用户所有评分数据
    public ResponseResult<List<Rating>> findAllRatingByUserId(int userId){
        ;
       return new ResponseResult<>(200,"查询成功",this.ratingService.getRatingsByUserId(userId));
    }

    //用户第一次选择genres偏好
    public  void choosePrefer(int userId,String genres){
        this.userFeaturesService.updateUserMatrix(userId,genres);
    }
}
